package com.qf.util;

import com.qf.entity.SysPermission;
import com.qf.entity.SysUser;
import com.qf.service.SysRoleService;
import com.qf.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 2019/9/25
 * Administrator
 * ssm0923
 * 面向对象面向君  不负代码不负卿
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @Override  //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        //SimpleAuthorizationInfo 封装用户的正确的角色和访问权限的字符信息
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        //1.得到认证通过的用户信息
        SysUser user = (SysUser) principalCollection.getPrimaryPrincipal();
        //2.根据用户名查询用户权限（角色和访问权限）->调用service
        List<String> rolenameList = sysRoleService.findroles(user.getId());
        //2.1 添加角色列表
        simpleAuthorizationInfo.addRoles(rolenameList);
        //2.2 访问权限
        for (String s : rolenameList) {
            List<SysPermission> menulist = sysUserService.findmenus(s);
            for (SysPermission sysPermission : menulist) {
                 simpleAuthorizationInfo.addStringPermission(sysPermission.getPercode());
               // System.out.println(sysPermission.getPercode()+"-menu");
            }
        }
        for (String s : rolenameList) {
            List<SysPermission> permissions = sysUserService.findPermission(s);
            for (SysPermission sysPermission : permissions) {
                simpleAuthorizationInfo.addStringPermission(sysPermission.getPercode());
            //    System.out.println(sysPermission.getPercode()+"-perms");
            }
        }

        return simpleAuthorizationInfo;
    }

    @Override   //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String username =(String) authenticationToken.getPrincipal();//接受的是输入的用户名
        SysUser user = sysUserService.login(username);
        System.out.println(user+","+username);
        if(user==null){
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassWord(), ByteSource.Util.bytes(user.getSalt()),"myrealm");
    }
}
